//
//  SearchParkViewController.m
//  SXH
//
//  Created by Jack on 15/9/7.
//  Copyright (c) 2015年 lyss. All rights reserved.
//

#import "SelectParkViewController.h"
#import "DBSearchParkHistory.h"
#import "CommonService.h"
#import "UIImageView+WebCache.h"
#import "ParkEntity.h"
#import "SelectTableViewCell.h"

#import "HistorySearchTableViewCell.h"


#define SEARCH_HOSTORY      @"搜索历史"

@interface SelectParkViewController ()<UITextFieldDelegate>{
    BOOL showRes;
}


@property (nonatomic, strong) IBOutlet UITableView *tableViewRes;
@property (nonatomic, strong) IBOutlet UIView *viewSearch;
@property (nonatomic, strong) IBOutlet UITextField *textFieldKey;
@property (nonatomic, strong) NSMutableArray *mutableArrayResult;

@end

@implementation SelectParkViewController
@synthesize viewSearch, textFieldKey, tableViewRes;
@synthesize mutableArrayResult;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    showRes = NO;
    
    mutableArrayResult = [[NSMutableArray alloc] init];
    
    [self searchParkData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark -
#pragma mark Table view data source

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (showRes != YES) {
        return 30.0;
    }
    return 0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (showRes != YES) {
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 30)];
        bgView.backgroundColor = [UIColor colorWithRed:0.91 green:0.93 blue:0.95 alpha:1];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(13, 0, 250, 30)];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.textColor = [UIColor darkGrayColor];
        titleLabel.font = [UIFont systemFontOfSize:13];
        titleLabel.text = @"搜索历史";
        
        [bgView addSubview:titleLabel];
    
        return bgView;
    }
    return self.view;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
   return [mutableArrayResult count];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (showRes == YES) {
        static NSString *CellIdentifier = @"SelectTableViewCell";
        SelectTableViewCell *cell = (SelectTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"SelectTableViewCell" owner:self options:nil];
            cell = [array objectAtIndex:0];
        }
        ParkEntity *parkEntity = [mutableArrayResult objectAtIndex:indexPath.row];
        
        [cell.parkImage sd_setImageWithURL:[NSURL URLWithString:parkEntity.album_thumb]];
        cell.parkName.text = parkEntity.title;
        if([parkEntity.is_business isEqualToString:@"1"] == YES){
            cell.parkIntroduce.text = @"与本APP合作";
        }else{
            cell.parkIntroduce.text = @"未与本APP合作";
        }
        
        return cell;
        
    }else {
        static NSString *CellIdentifier = @"HistorySearchTableViewCell";
        HistorySearchTableViewCell *cell = (HistorySearchTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"HistorySearchTableViewCell" owner:self options:nil];
            cell = [array objectAtIndex:0];
        }
        
        if (indexPath.row == [mutableArrayResult count]-1) {
            cell.labelTitle.hidden = YES;
            cell.imageViewSearch.hidden = YES;
        } else {
            cell.labelRemove.hidden = YES;
            cell.imageViewRemove.hidden = YES;
            
            NSString *searchKey = [mutableArrayResult objectAtIndex:indexPath.row];
            cell.labelTitle.text = searchKey;
        }
        return cell;
    
//        static NSString *CellIdentifier = @"Cell";
//        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//        if (cell == nil) {
//            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
//            cell.backgroundColor = [UIColor clearColor];
//            cell.contentView.backgroundColor = [UIColor whiteColor];
//            //cell.selectionStyle = UITableViewCellSelectionStyleNone;
//            
//            [cell.textLabel setTextColor:[UIColor blackColor]];
//            cell.textLabel.font = [UIFont systemFontOfSize:15];
//        }
//        
//        NSString *parkHistory = [mutableArrayResult objectAtIndex:indexPath.row];
//        
//        cell.textLabel.text = parkHistory;
//        
//        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (showRes != YES) {
        return 44;
    }else{
        return 100;
    }
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (showRes == YES) {
        ParkEntity *entity = [mutableArrayResult objectAtIndex:indexPath.row];
        [self.navigationController popViewControllerAnimated:YES];

        [_rfVC.parkSelect setTitle:entity.title forState: UIControlStateNormal];
        
        [DBSearchParkHistory createTable];
        [DBSearchParkHistory saveOrUpdataEntity:entity.title];

        [tableViewRes reloadData];
    } else {
        if (indexPath.row == [mutableArrayResult count] - 1) {
            [mutableArrayResult removeAllObjects];
            [DBSearchParkHistory deleteDataBase];
            [tableViewRes reloadData];
        }else{
            [self.navigationController popViewControllerAnimated:YES];
            [_rfVC.parkSelect setTitle:[mutableArrayResult objectAtIndex:indexPath.row]forState: UIControlStateNormal];
        }
    
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (textFieldKey.text.length > 0) {
        [self searchParkData];
        showRes = YES;
    }
    
    [textFieldKey resignFirstResponder];
    return YES;
}

-(IBAction)SearchPark:(id)sender {
    if (textFieldKey.text.length > 0) {
        [self searchParkData];
        showRes = YES;
    }
}

- (void) searchParkData {
    
    CommonService *service = [[CommonService alloc] init];
    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                           textFieldKey.text, @"title",nil];
    if(textFieldKey.text.length == 0){
        [mutableArrayResult removeAllObjects];
        mutableArrayResult = [DBSearchParkHistory selectAllSearchRes];
        [mutableArrayResult addObject:@""];
        [tableViewRes reloadData];
    }else{
        [service getNetWorkData:param
                           Path:PARKPATH
                      Successed:^(id entity) {
                          NSDictionary *dic = (NSDictionary *)entity;
                          
                          NSArray *array = [dic objectForKey:@"rows"];
                          
                          [mutableArrayResult removeAllObjects];
                          
                          for (NSDictionary* attributes in array) {
                              ParkEntity *parkEntity = [[ParkEntity alloc] init];
                              parkEntity = [parkEntity initWithAttributes:attributes];
                              [mutableArrayResult addObject:parkEntity];
                          }
                          
                          [tableViewRes reloadData];
                          
                      } Failed:^(NSInteger errorCode, NSString *message) {
                          DebugLog(@"%@", message);
                      }];
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"SelectParkViewController"];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"SelectParkViewController"];
}
@end
